﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSiteFool.Models;
using WebSiteFool.DAL;
using WebMatrix.WebData;
using WebSiteFool.Filters;
using System.ServiceModel.Syndication;
using WebSiteFool.Libs;

namespace WebSiteFool.Controllers
{
    [InitializeSimpleMembership]
    public class ArticleController : BaseController
    {
        //
        // GET: /Article/

        public ActionResult Index()
        {
            return View();
        }

        [RestrictAuthorize(Roles = "SuperWoman")]
        public ActionResult Create()
        {
            return View();
        }

        [RestrictAuthorize(Roles = "SuperWoman")]
        public ActionResult List()
        {
            return View(DbWorker.ArticleRepository.Get(orderBy: OrderByCreateDateDesc));
        }

        public ActionResult Show(Guid id)
        {
            var article = DbWorker.ArticleRepository.Get(m => m.Id == id, includeProperties: "Comments,Visits").FirstOrDefault();
            UserProfile user;
            if (WebSecurity.HasUserId)
            {
                user = DbWorker.UserRespository.GetById(WebSecurity.CurrentUserId);
                DbWorker.VisitRecordRepository.Insert(new VisitRecord() { Article = article, Id = Guid.NewGuid(), CreateTime = DateTime.UtcNow, User = user });
            }
            else
            {
                DbWorker.VisitRecordRepository.Insert(new VisitRecord() { Article = article, Id = Guid.NewGuid(), CreateTime = DateTime.UtcNow });
            }
            DbWorker.Save();
            return View(article);
        }

        [HttpPost]
        [RestrictAuthorize(Roles = "SuperWoman")]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Article article)
        {
            if (!ModelState.IsValid)
            {
                return View(article);
            }
            article.CreateDate = DateTime.UtcNow;
            article.UpdateDate = DateTime.UtcNow;
            DbWorker.ArticleRepository.Insert(article);
            DbWorker.Save();
            return RedirectToAction("List");
        }

        [RestrictAuthorize(Roles = "SuperWoman")]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(Guid id)
        {
            DbWorker.ArticleRepository.Delete(id);
            DbWorker.Save();
            return RedirectToAction("List");
        }


        [RestrictAuthorize(Roles = "SuperWoman")]
        public ActionResult Edit(Guid id)
        {
            var article = DbWorker.ArticleRepository.GetById(id);
            if (article != null)
            {
                return View(article);
            }
            return RedirectToAction("Error");
        }

        [HttpPost]
        [RestrictAuthorize(Roles = "SuperWoman")]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Article article)
        {
            var orignArticle = DbWorker.ArticleRepository.GetById(article.Id);
            orignArticle.Title = article.Title;
            orignArticle.Content = article.Content;
            orignArticle.UpdateDate = DateTime.Now;
            DbWorker.ArticleRepository.Update(orignArticle);
            DbWorker.Save();
            return RedirectToAction("List");
        }

        public ActionResult Feed()
        {
            SyndicationFeed feed = new SyndicationFeed();
            IList<SyndicationItem> items = new List<SyndicationItem>();
            var articles = DbWorker.ArticleRepository.Get(orderBy: OrderByCreateDateDesc);
            foreach (var item in articles)
            {
                var syndicationItem = new SyndicationItem()
                {
                    Id = item.Id.ToString(),
                    Title = new TextSyndicationContent(item.Title),
                    PublishDate = new DateTimeOffset(item.CreateDate),
                    LastUpdatedTime = new DateTimeOffset(item.UpdateDate),
                    Content = SyndicationContent.CreateHtmlContent(item.Content)
                };
                syndicationItem.AddPermalink(new Uri(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, "/Article/Show/" + item.Id)));
                items.Add(syndicationItem);

            }
            feed.Items = items;
            feed.Language = "en-us";
            feed.Title = new TextSyndicationContent("TangJing.info - Looking for simple & free...");

            return new RssActionResult(feed);
        }

        private IOrderedQueryable<Article> OrderByCreateDateDesc(IQueryable<Article> articles)
        {
            return articles.OrderByDescending(item => item.CreateDate);
        }
    }
}
